<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="XlCustomerStoreInfoForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="门店编码" v-bind="validateInfos.storeCode" id="XlCustomerStoreInfoForm-storeCode"
                name="storeCode">
                <a-input v-model:value="formData.storeCode" placeholder="系统自动获取" disabled allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="门店名称" v-bind="validateInfos.storeName" id="XlCustomerStoreInfoForm-storeName"
                name="storeName">
                <a-input v-model:value="formData.storeName" placeholder="请输入门店名称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="所属客户" v-bind="validateInfos.customerId" id="XlCustomerStoreInfoForm-customerId"
                name="customerId">
                <j-search-select v-model:value="formData.customerId" dict="xl_customer_info,customer_name,id"
                  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="所在地区" v-bind="validateInfos.province" id="XlCustomerStoreInfoForm-province"
                name="province">
                <j-area-linkage v-model:value="formData.province" placeholder="请选择省市区" saveCode="region" allow-clear @change="onProvinceChange" />
              </a-form-item>

            </a-col>
            <a-col :span="24">
              <a-form-item label="门店详细地址" v-bind="validateInfos.storeAddress" id="XlCustomerStoreInfoForm-storeAddress"
                name="storeAddress">
                <a-input id="searchInputId" v-model:value="formData.storeAddress" placeholder="请输入门店系统地址" allow-clear
                  @change="storeAddressChange"></a-input>
                <div id="container" style="height: 300px;display: none" ></div>
              </a-form-item>
              <!-- 用于展示地图的容器 -->
            </a-col>
            <a-col :span="24">
              <a-form-item label="门店地址经纬度" v-bind="validateInfos.storeCoordinates"
                id="XlCustomerStoreInfoForm-storeCoordinates" name="storeCoordinates">
                <a-input v-model:value="formData.storeCoordinates" placeholder="系统自动获取" disabled allow-clear></a-input>
              </a-form-item>
            </a-col>


            <a-col :span="24">
              <a-form-item label="门店面积" v-bind="validateInfos.storeArea" id="XlCustomerStoreInfoForm-storeArea"
                name="storeArea">
                <a-input v-model:value="formData.storeArea" placeholder="请输入门店面积" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="门店负责人" v-bind="validateInfos.storeManager" id="XlCustomerStoreInfoForm-storeManager"
                name="storeManager">
                <a-input v-model:value="formData.storeManager" placeholder="请输入门店负责人" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="门店负责人电话" v-bind="validateInfos.storeManagerPhone"
                id="XlCustomerStoreInfoForm-storeManagerPhone" name="storeManagerPhone">
                <a-input v-model:value="formData.storeManagerPhone" placeholder="请输入门店负责人电话" allow-clear></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, onUnmounted, createApp } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
import JAreaLinkage from '/@/components/Form/src/jeecg/components/JAreaLinkage.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../XlCustomerStoreInfo.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
const { notification } = useMessage();
//map 
import AMapLoader from '@amap/amap-jsapi-loader';
 
let map = null;
// 初始化高德地图的AutoComplete插件
let autoComplete = ref(null);
let provinceText = ""; 
onMounted(() => {
  // window._AMapSecurityConfig = {
  //         securityJsCode:'7bb55897892a7749c6257dae6dabb93c',
  //     }
  AMapLoader.load({
    //key: "acc1c5237950fef80550cc9fc2125bfa", //申请好的Web端开发者 Key，调用 load 时必填
    key: "4ca83211492407d5a5b1bb7e18283c27",
    //version: "1.4.15", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    version: "2.0",
    plugins: ["AMap.AutoComplete", //输入提示插件
      "AMap.PlaceSearch", //POI搜索插件
      "AMap.Scale", //右下角缩略图插件 比例尺
      "AMap.OverView", //地图鹰眼插件
      "AMap.ToolBar", //地图工具条
      "AMap.Geolocation", //定位控件，用来获取和展示用户主机所在的经纬度位置
      "AMap.Geocoder"], // 逆地理编码,通过经纬度获取地址所在位置详细信息],
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 14, // 初始化地图级别
        zoomEnable: true,
        center: [113.326548,23.137301], // 初始化地图中心点位置
      });
      var autoOptions = {
        //input: "searchInputId",
      };
      autoComplete = new AMap.AutoComplete(autoOptions);
      autoComplete.on("select", function (e) {
          //针对选中的poi实现自己的功能
          //console.log(e.poi.name);
          //console.log(e.poi);
          formData.storeAddress=e.poi.name;
          let storeCoordinates =  e.poi.location.lng +","+e.poi.location.lat;
          formData.storeCoordinates = storeCoordinates;
          let choosePoint = new AMap.LngLat(e.poi.location.lng, e.poi.location.lat);
          const marker = new AMap.Marker({
            position: choosePoint, //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: e.poi.name
          });
          map.setCenter(choosePoint);
          map.add(marker);
      });
    })
    .catch((e) => {
      console.error(e); //加载错误提示
    });
});

function storeAddressChange(e) {
  if(provinceText ===""){
    createMessage.error(('请先选择所在地区'));
    //return;
  }
  autoComplete.setCity(provinceText);
  const fulladdr = provinceText+formData.storeAddress;
  console.log(fulladdr);
  
  autoComplete.search(fulladdr, function (status, result) {
  })
  //调用map搜索
}
function onProvinceChange(e) {
  if(e === undefined){
    provinceText = "";
  }else{
    let provinceArr = getAreaTextByCode(e).split("/");
    provinceText = getAreaTextByCode(e).replaceAll("/", "");
  }
}

// map

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  storeCode: '',
  storeName: '',
  customerId: undefined,
  province: '',
  storeAddress: '',
  storeCoordinates: '',
  storeArea: '',
  storeManager: '',
  storeManagerPhone: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  storeCode: [{ required: false, message: '请输入门店编码!' },],
  storeName: [{ required: true, message: '请输入门店名称!' },],
  province: [{ required: true, message: '请输入省市区!' },],
  storeAddress: [{ required: true, message: '请输入门店系统地址!' },],
  storeManager: [{ required: true, message: '请输入门店负责人!' },],
  storeManagerPhone: [{ required: true, message: '请输入门店负责人电话!' },],
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});


/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}
</style>
